<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <TreeTools :tree="company" :is-root="true" class="header" @addDep="addDepFn" />
        <el-tree :data="depts" :props="defaultProps" default-expand-all>
          <template v-slot="{data}">
            <TreeTools :tree="data" @deDeps="getDepartments" @addDep="addDepFn" @deitDep="deitDepFn" /></template>
        </el-tree>
      </el-card>
    </div>
    <AddDep ref="addDep" :visible.sync="addVisible" :current-node="currentNode" :origin="originDepts" />
  </div>
</template>

<script>
// import treeTools from './components/TreeTools.vue'
import TreeTools from './components/TreeTools'
import AddDep from './components/AddDep.vue'
import { getDepartments } from '@/api/department'
import { tranListToTreeDate } from '@/utils/index'
export default {
  components: {
    TreeTools,
    AddDep
  },
  data() {
    return {
      defaultProps: {
        label: 'name'
      },
      company: {
        name: '传智教育'
      },
      depts: [],
      addVisible: false,
      currentNode: {},
      originDepts: [] // 最原始的部门数据 传给AddDep组件使用
    }
  },

  created() {
    this.getDepartments()
  },

  methods: {
    async getDepartments() {
      try {
        this.loading = true
        const res = await getDepartments()
        console.log(res)
        this.originDepts = res.depts
        this.depts = tranListToTreeDate(res.depts, '')
        this.company = { name: res.companyName, manager: '负责人', children: this.depts }
        console.log(this.depts)
      } finally {
        this.loading = false
      }
    },
    addDepFn(currentNode) {
      // console.log('新增')
      this.addVisible = true
      this.currentNode = currentNode
    },
    deitDepFn(currentNode) {
      // console.log('edit', currentNode)
      this.addVisible = true
      // 把当前节点的东西都赋值给formData
      this.$refs.addDep.formData = { ...currentNode, children: '' }
    }
  }
}
</script>

<style scoped lang="scss">
.tree-card {
  padding: 30px  60px;
  font-size:14px;
  .header {
    height: 30px;
  }
}
</style>
